import React, { useState, useEffect } from 'react';
import {
  Layout,
  Menu,
  Breadcrumb,
  Table,
  Form,
  Input,
  Button,
  Select,
  DatePicker,
  Checkbox,
  Radio,
  Switch,
  Modal,
  Card,
  Avatar,
  Badge,
  Tag,
  Divider,
  Tabs,
  Steps,
  message,
  notification,
  Popconfirm,
  Upload,
  Tree,
  Pagination,
  Statistic,
  Row,
  Col,
  Space,
  Dropdown,
  Tooltip
} from 'antd';
import {
  UserOutlined,
  LaptopOutlined,
  NotificationOutlined,
  UploadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  DownloadOutlined,
  InfoCircleOutlined,
  SettingOutlined,
  EllipsisOutlined
} from '@ant-design/icons';

const { Header, Content, Sider, Footer } = Layout;
const { SubMenu } = Menu;
const { Option } = Select;
const { TabPane } = Tabs;
const { Step } = Steps;
const { TextArea } = Input;
const { Meta } = Card;
const { DirectoryTree } = Tree;

const App = () => {
  // 状态管理
  const [collapsed, setCollapsed] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [activeTab, setActiveTab] = useState('1');
  const [form] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  
  // 模拟数据
  const dataSource = [
    {
      key: '1',
      name: '张三',
      age: 32,
      address: '上海市普陀区金沙江路 1518 弄',
      status: 'active',
      tags: ['优秀', '开发']
    },
    {
      key: '2',
      name: '李四',
      age: 42,
      address: '北京市海淀区中关村',
      status: 'inactive',
      tags: ['测试']
    },
    {
      key: '3',
      name: '王五',
      age: 28,
      address: '广州市天河区体育中心',
      status: 'active',
      tags: ['UI', '设计']
    },
  ];

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: text => <a>{text}</a>,
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
      sorter: (a, b) => a.age - b.age,
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: status => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '活跃' : '不活跃'}
        </Tag>
      ),
    },
    {
      title: '标签',
      key: 'tags',
      dataIndex: 'tags',
      render: tags => (
        <>
          {tags.map(tag => {
            let color = tag.length > 5 ? 'geekblue' : 'green';
            if (tag === '测试') {
              color = 'volcano';
            }
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Tooltip title="编辑">
            <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record.key)} />
          </Tooltip>
          <Popconfirm
            title="确定要删除吗?"
            onConfirm={() => handleDelete(record.key)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />} />
          </Popconfirm>
          <Dropdown
            menu={{
              items: [
                { key: '1', label: '查看详情' },
                { key: '2', label: '导出数据' },
                { key: '3', label: '设为管理员' },
              ],
            }}
          >
            <Button>更多 <DownloadOutlined /></Button>
          </Dropdown>
        </Space>
      ),
    },
  ];

  // 事件处理
  const handleEdit = (key) => {
    message.info(`编辑用户 ${key}`);
    setModalVisible(true);
  };

  const handleDelete = (key) => {
    message.success(`删除用户 ${key} 成功`);
  };

  const onFinish = (values) => {
    console.log('表单提交:', values);
    notification.success({
      message: '表单提交成功',
      description: '您的数据已成功提交到服务器。',
    });
  };

  const onFinishFailed = (errorInfo) => {
    console.log('表单验证失败:', errorInfo);
  };

  const showModal = () => {
    setModalVisible(true);
  };

  const handleOk = () => {
    setModalVisible(false);
    message.success('操作成功');
  };

  const handleCancel = () => {
    setModalVisible(false);
  };

  const onSelectChange = (newSelectedRowKeys) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  // 树形结构数据
  const treeData = [
    {
      title: '父节点1',
      key: '0-0',
      children: [
        {
          title: '子节点1',
          key: '0-0-0',
          isLeaf: true,
        },
        {
          title: '子节点2',
          key: '0-0-1',
          isLeaf: true,
        },
      ],
    },
    {
      title: '父节点2',
      key: '0-1',
      children: [
        {
          title: '子节点3',
          key: '0-1-0',
          isLeaf: true,
        },
      ],
    },
  ];

  return (
    <Layout style={{ minHeight: '100vh' }}>
      {/* 顶部导航 */}
      <Header className="header">
        <div className="logo" />
        <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']}>
          <Menu.Item key="1">首页</Menu.Item>
          <Menu.Item key="2">仪表盘</Menu.Item>
          <Menu.Item key="3">系统设置</Menu.Item>
        </Menu>
      </Header>
      
      <Layout>
        {/* 侧边栏 */}
        <Sider width={200} collapsible collapsed={collapsed} onCollapse={setCollapsed}>
          <Menu
            mode="inline"
            defaultSelectedKeys={['1']}
            defaultOpenKeys={['sub1']}
            style={{ height: '100%', borderRight: 0 }}
          >
            <SubMenu key="sub1" icon={<UserOutlined />} title="用户管理">
              <Menu.Item key="1">用户列表</Menu.Item>
              <Menu.Item key="2">角色管理</Menu.Item>
              <Menu.Item key="3">权限设置</Menu.Item>
            </SubMenu>
            <SubMenu key="sub2" icon={<LaptopOutlined />} title="系统管理">
              <Menu.Item key="5">系统设置</Menu.Item>
              <Menu.Item key="6">日志管理</Menu.Item>
              <Menu.Item key="7">备份恢复</Menu.Item>
            </SubMenu>
            <SubMenu key="sub3" icon={<NotificationOutlined />} title="消息中心">
              <Menu.Item key="9">通知公告</Menu.Item>
              <Menu.Item key="10">站内信</Menu.Item>
            </SubMenu>
          </Menu>
        </Sider>
        
        <Layout style={{ padding: '0 24px 24px' }}>
          {/* 面包屑导航 */}
          <Breadcrumb style={{ margin: '16px 0' }}>
            <Breadcrumb.Item>首页</Breadcrumb.Item>
            <Breadcrumb.Item>用户管理</Breadcrumb.Item>
            <Breadcrumb.Item>用户列表</Breadcrumb.Item>
          </Breadcrumb>
          
          <Content
            style={{
              background: '#fff',
              padding: 24,
              margin: 0,
              minHeight: 280,
            }}
          >
            {/* 标签页 */}
            <Tabs activeKey={activeTab} onChange={setActiveTab}>
              <TabPane tab="用户列表" key="1">
                {/* 操作区域 */}
                <div style={{ marginBottom: 16 }}>
                  <Space>
                    <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>
                      新建用户
                    </Button>
                    <Button icon={<DownloadOutlined />}>导出数据</Button>
                    <Button danger disabled={selectedRowKeys.length === 0}>
                      批量删除
                    </Button>
                    <Badge count={5} size="small">
                      <Button>通知中心</Button>
                    </Badge>
                  </Space>
                </div>
                
                {/* 表格 */}
                <Table
                  rowSelection={rowSelection}
                  columns={columns}
                  dataSource={dataSource}
                  pagination={false}
                />
                
                {/* 分页 */}
                <div style={{ marginTop: 16, textAlign: 'right' }}>
                  <Pagination
                    current={currentPage}
                    total={50}
                    showSizeChanger
                    showQuickJumper
                    onChange={handlePageChange}
                    showTotal={total => `共 ${total} 条`}
                  />
                </div>
              </TabPane>
              
              <TabPane tab="表单" key="2">
                {/* 表单 */}
                <Card title="用户表单" bordered={false}>
                  <Form
                    form={form}
                    name="basic"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 12 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                  >
                    <Form.Item
                      label="用户名"
                      name="username"
                      rules={[{ required: true, message: '请输入用户名!' }]}
                    >
                      <Input placeholder="请输入用户名" />
                    </Form.Item>

                    <Form.Item
                      label="密码"
                      name="password"
                      rules={[{ required: true, message: '请输入密码!' }]}
                    >
                      <Input.Password placeholder="请输入密码" />
                    </Form.Item>

                    <Form.Item
                      label="年龄"
                      name="age"
                      rules={[{ required: true, message: '请输入年龄!' }]}
                    >
                      <Input type="number" min="1" max="120" />
                    </Form.Item>

                    <Form.Item
                      label="性别"
                      name="gender"
                      rules={[{ required: true, message: '请选择性别!' }]}
                    >
                      <Radio.Group>
                        <Radio value="male">男</Radio>
                        <Radio value="female">女</Radio>
                        <Radio value="other">其他</Radio>
                      </Radio.Group>
                    </Form.Item>

                    <Form.Item
                      label="角色"
                      name="role"
                      rules={[{ required: true, message: '请选择角色!' }]}
                    >
                      <Select placeholder="请选择角色">
                        <Option value="admin">管理员</Option>
                        <Option value="user">普通用户</Option>
                        <Option value="guest">访客</Option>
                      </Select>
                    </Form.Item>

                    <Form.Item label="生日" name="birthday">
                      <DatePicker style={{ width: '100%' }} />
                    </Form.Item>

                    <Form.Item label="兴趣爱好" name="hobbies">
                      <Checkbox.Group>
                        <Checkbox value="reading">阅读</Checkbox>
                        <Checkbox value="coding">编程</Checkbox>
                        <Checkbox value="music">音乐</Checkbox>
                        <Checkbox value="sports">运动</Checkbox>
                      </Checkbox.Group>
                    </Form.Item>

                    <Form.Item label="描述" name="description">
                      <TextArea rows={4} placeholder="请输入个人描述" />
                    </Form.Item>

                    <Form.Item label="是否激活" name="active" valuePropName="checked">
                      <Switch />
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 6, span: 12 }}>
                      <Space>
                        <Button type="primary" htmlType="submit">
                          提交
                        </Button>
                        <Button htmlType="button" onClick={() => form.resetFields()}>
                          重置
                        </Button>
                      </Space>
                    </Form.Item>
                  </Form>
                </Card>
              </TabPane>
              
              <TabPane tab="其他组件" key="3">
                {/* 卡片组 */}
                <Row gutter={16}>
                  <Col span={8}>
                    <Card 
                      title="用户统计" 
                      bordered={false}
                      actions={[
                        <SettingOutlined key="setting" />,
                        <EditOutlined key="edit" />,
                        <EllipsisOutlined key="ellipsis" />,
                      ]}
                    >
                      <Statistic title="用户总数" value={1256} />
                      <Statistic title="活跃用户" value={873} style={{ marginTop: 16 }} />
                      <Statistic title="新增用户" value={56} style={{ marginTop: 16 }} />
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card 
                      title="任务进度" 
                      bordered={false}
                      extra={<a href="#">更多</a>}
                    >
                      <Steps current={currentStep} direction="vertical">
                        <Step title="注册" description="已完成" />
                        <Step title="验证" description="已完成" />
                        <Step title="完善信息" description="进行中" />
                        <Step title="完成" description="等待" />
                      </Steps>
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card
                      cover={
                        <img
                          alt="example"
                          src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
                        />
                      }
                      actions={[
                        <Button type="link" icon={<DownloadOutlined />}>下载</Button>,
                        <Button type="link" icon={<EditOutlined />}>编辑</Button>,
                        <Button type="link" icon={<InfoCircleOutlined />}>详情</Button>,
                      ]}
                    >
                      <Meta
                        avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
                        title="卡片标题"
                        description="这是卡片描述内容"
                      />
                    </Card>
                  </Col>
                </Row>
                
                <Divider orientation="left">文件上传</Divider>
                
                <Upload
                  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                  listType="picture"
                  defaultFileList={[
                    {
                      uid: '1',
                      name: 'xxx.png',
                      status: 'done',
                      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                    },
                    {
                      uid: '2',
                      name: 'yyy.png',
                      status: 'error',
                    },
                  ]}
                >
                  <Button icon={<UploadOutlined />}>上传文件</Button>
                </Upload>
                
                <Divider orientation="left">树形控件</Divider>
                
                <DirectoryTree
                  multiple
                  defaultExpandAll
                  treeData={treeData}
                />
              </TabPane>
            </Tabs>
            
            {/* 模态框 */}
            <Modal
              title="新建用户"
              visible={modalVisible}
              onOk={handleOk}
              onCancel={handleCancel}
              width={800}
              footer={[
                <Button key="back" onClick={handleCancel}>
                  取消
                </Button>,
                <Button key="submit" type="primary" onClick={handleOk}>
                  提交
                </Button>,
              ]}
            >
              <Form layout="vertical">
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      label="用户名"
                      name="username"
                      rules={[{ required: true, message: '请输入用户名' }]}
                    >
                      <Input placeholder="请输入用户名" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="密码"
                      name="password"
                      rules={[{ required: true, message: '请输入密码' }]}
                    >
                      <Input.Password placeholder="请输入密码" />
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      label="邮箱"
                      name="email"
                      rules={[{ type: 'email', message: '请输入有效的邮箱地址' }]}
                    >
                      <Input placeholder="请输入邮箱" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="手机号"
                      name="phone"
                    >
                      <Input placeholder="请输入手机号" />
                    </Form.Item>
                  </Col>
                </Row>
                <Form.Item
                  label="备注"
                  name="remark"
                >
                  <TextArea rows={4} placeholder="请输入备注" />
                </Form.Item>
              </Form>
            </Modal>
          </Content>
          
          {/* 页脚 */}
          <Footer style={{ textAlign: 'center' }}>
            Ant Design ©2023 Created by Ant UED
          </Footer>
        </Layout>
      </Layout>
    </Layout>
  );
};

export default App;
